package org.dromara.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUserAddress;
import org.dromara.system.domain.bo.SysUserAddressBo;
import org.dromara.system.domain.vo.SysUserAddressVo;
import org.dromara.system.enums.MachineConstant;
import org.dromara.system.mapper.SysUserAddressMapper;
import org.dromara.system.service.ISysUserAddressService;
import org.dromara.system.service.impl.permission.PermissionBaseService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 地址Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserAddressServiceImpl extends ServiceImpl<SysUserAddressMapper, SysUserAddress> implements ISysUserAddressService {

    private final PermissionBaseService permissionBaseService;

    /**
     * 查询地址
     *
     * @param id 主键
     * @return 地址
     */
    @Override
    public SysUserAddressVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询地址列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 地址分页列表
     */
    @Override
    public TableDataInfo<SysUserAddressVo> queryPageList(SysUserAddressBo bo, PageQuery pageQuery) {
        permissionBaseService.aloneAssignPermission(bo);
        IPage<SysUserAddressVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SysUserAddressVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    /**
     * 查询符合条件的地址列表
     *
     * @param bo 查询条件
     * @return 地址列表
     */
    @Override
    public List<SysUserAddressVo> queryList(SysUserAddressBo bo) {
        LambdaQueryWrapper<SysUserAddress> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserAddress> buildQueryWrapper(SysUserAddressBo bo) {
        LambdaQueryWrapper<SysUserAddress> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysUserAddress::getId);
        lqw.eq(bo.getUserId() != null, SysUserAddress::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getAddressName()), SysUserAddress::getAddressName, bo.getAddressName());
        lqw.eq(StringUtils.isNotBlank(bo.getAddressPhone()), SysUserAddress::getAddressPhone, bo.getAddressPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getAddressLocation()), SysUserAddress::getAddressLocation, bo.getAddressLocation());
        lqw.eq(StringUtils.isNotBlank(bo.getAddressDetailed()), SysUserAddress::getAddressDetailed, bo.getAddressDetailed());
        lqw.eq(bo.getIsDefaultAddress() != null, SysUserAddress::getIsDefaultAddress, bo.getIsDefaultAddress());
        return lqw;
    }

    /**
     * 新增地址
     *
     * @param bo 地址
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysUserAddressBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        SysUserAddress add = MapstructUtils.convert(bo, SysUserAddress.class);
        if (ObjectUtil.equal(add.getIsDefaultAddress(), MachineConstant.NUMBER.ONE)) {
            lambdaUpdate()
                .set(SysUserAddress::getIsDefaultAddress, MachineConstant.NUMBER.ZERO)
                .eq(SysUserAddress::getUserId, bo.getUserId())
                .update();
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改地址
     *
     * @param bo 地址
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysUserAddressBo bo) {
        SysUserAddress update = MapstructUtils.convert(bo, SysUserAddress.class);
        if (ObjectUtil.equal(update.getIsDefaultAddress(), MachineConstant.NUMBER.ONE)) {
            lambdaUpdate()
                .set(SysUserAddress::getIsDefaultAddress, MachineConstant.NUMBER.ZERO)
                .eq(SysUserAddress::getUserId, bo.getUserId())
                .ne(SysUserAddress::getId, bo.getId())
                .update();
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserAddress entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除地址信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
